package net.ssta.core.web;

import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import net.ssta.core.config.Config;

import org.apache.log4j.Logger;

public class ExceptionHandler
{
	protected static Logger log =Logger.getLogger(ExceptionHandler.class);
	public static void handleException(Exception e, ServletRequest request, ServletResponse response)
	{
//		Exception rootCause = getRootCause(e);
//		log.error(rootCause.toString(),e);
//		Exception exception = new Exception(rootCause.toString(), e);
//		request.setAttribute("exception", exception);
//		request.setAttribute("exception", e);
//		this.forward("/jsp/common/errorPage.jsp");
		response.setContentType("text/html;charset=GBK");
		PrintWriter pw = null;
		try
		{
			pw = response.getWriter();
			pw.println("");
			pw.println("this message is print by ReqeustMonitorFilter,something maybe wrong!");
			pw.println("the root exception message is " + e.toString());
			pw.println("the following is the exception stack trace:");
			StackTraceElement[] stack = e.getStackTrace();
			for(int i = 0; i<stack.length ;i++)
			{
				StackTraceElement element = stack[i];
				pw.println(element.getClassName() + "." + element.getMethodName() + "(" + element.getFileName() + ":" + element.getLineNumber() + ")");
				if("net.ssta.core.web.RequestMonitorFilter".equals(element.getClassName()))
				{
					pw.println("......");
					break;
				}
			}
			
		}
		catch(Exception newe)
		{
			
		}
		finally
		{
			if(pw != null) pw.close();
		}
		
	}
	
	
	public static Exception getRootCause(Exception e)
	{
		Exception eCurrentException = e;
		Exception eRootException = null; 
	
		while(eCurrentException != null)
		{
			Exception eNextLevelUp = (Exception)eCurrentException.getCause();
			if(eNextLevelUp == null)
			{
				eRootException = eCurrentException;
				break;
			}
			else
			{
				eCurrentException = eNextLevelUp;
			}
		}
		return eRootException;
	}
}
